#include <Arduino.h>
#include "SimpleTask.h"

Task SimpleTask::_taskList[TASK_MAX_NUM] = {0};

/**
 * @brief Create task scheduler
 */
SimpleTask::SimpleTask()
{
    for (int x = 0; x < TASK_MAX_NUM; x++) {
        _taskList[x].event = nullptr;
    }
}


/**
 * @brief Create task
 * @param event Task function
 * @param cycle Task cycle/tick
 */
void SimpleTask::createTask(Func event, unsigned long cycle)
{
    for (int x = 0; x < TASK_MAX_NUM; x++) {
        if (_taskList[x].event == nullptr) {
            _taskList[x].stat = TASK_STAT_READY;
            _taskList[x].preTime = 0;
            _taskList[x].cycle = cycle;
            _taskList[x].event = event;
            break;
        }
    }
}


/**
 * @brief Single task execution
 */
void SimpleTask::taskScheduler()
{
    unsigned long curTick = millis();

    for (int x = 0; x < TASK_MAX_NUM; x++) {
        if (_taskList[x].event == nullptr) continue;

        switch (_taskList[x].stat)
        {
        case TASK_STAT_READY: {
            if (curTick - _taskList[x].preTime > _taskList[x].cycle) {
                _taskList[x].stat = TASK_STAT_RUN;
                _taskList[x].preTime = curTick;
                _taskList[x].event();
                _taskList[x].stat = TASK_STAT_READY;
                break;
            }
        }
        case TASK_STAT_KILL:
        case TASK_STAT_RUN:
        case TASK_STAT_SUSPEND:
        default:
            break;
        }
    }
}

/**
 * @brief Periodic task execution
 */
void SimpleTask::taskRun()
{
    for( ;; ) {
        taskScheduler();
    }
}
